export type ToastType = "success" | "error" | "warning" | "info";

export interface ToastItem {
  id: number;
  type: ToastType;
  message: string;
  duration: number;
  dismissible: boolean;
}

export const useToast = () => {
  const toasts = useState<ToastItem[]>("toasts", () => []);

  const remove = (id: number) => {
    toasts.value = toasts.value.filter((t) => t.id !== id);
  };

  const clear = () => {
    toasts.value = [];
  };

  const show = (options: {
    message: string;
    type?: ToastType;
    duration?: number;
    dismissible?: boolean;
  }) => {
    const id = Date.now() + Math.floor(Math.random() * 1000);
    const item: ToastItem = {
      id,
      message: options.message,
      type: options.type ?? "info",
      duration: options.duration ?? 3000,
      dismissible: options.dismissible ?? true,
    };
    toasts.value = [item, ...toasts.value];
    if (import.meta.client && item.duration > 0) {
      window.setTimeout(() => remove(id), item.duration);
    }
    return id;
  };

  const success = (message: string, duration = 3000) =>
    show({ message, type: "success", duration });
  const error = (message: string, duration = 3000) =>
    show({ message, type: "error", duration });
  const warning = (message: string, duration = 3000) =>
    show({ message, type: "warning", duration });
  const info = (message: string, duration = 3000) =>
    show({ message, type: "info", duration });

  return { toasts, show, remove, clear, success, error, warning, info };
};

